package com.zhx.common.common.interceptor;


import cn.hutool.core.stream.CollectorUtil;
import com.zhx.common.common.domain.dto.RequestInfo;
import com.zhx.common.common.exception.HttpErrorEnum;
import com.zhx.common.common.util.RequestHolder;
import com.zhx.common.user.domain.enums.BlackTypeEnum;
import com.zhx.common.user.service.cache.UserCache;
import jodd.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

@Component
public class BlackInterceptor implements HandlerInterceptor {

    @Resource
    private UserCache userCache;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<Integer, Set<String>> blackMap = userCache.getBlackMap();
        RequestInfo requestInfo = RequestHolder.get();
        //如果用户在黑名单中，则拒绝访问
        if (inBlackList(requestInfo.getUid(), blackMap.get(BlackTypeEnum.UID.getType()))) {
            HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
            return false;
        }
        return true;
    }

    private boolean inBlackList(Long uid, Set<String> set) {
        if(Objects.isNull(uid) || CollectionUtils.isEmpty(set)) {
            return false;
        }
        return set.contains(uid.toString());
    }
}
